<template>
  <div class="upload-container">
    <!-- 文件选择按钮 -->
    <el-upload
      class="upload-box"
      action=""
      :auto-upload="false"
      :on-change="handleFileChange"
      :show-file-list="false"
      multiple
    >
      <el-button type="primary">选择文件</el-button>
    </el-upload>

    <!-- 上传按钮 -->
    <el-button
      type="success"
      :disabled="fileList.length === 0"
      @click="uploadFiles"
    >
      上传
    </el-button>

    <!-- 进度条 -->
    <el-progress
      v-if="uploading"
      :percentage="progress"
      :status="progress === 100 ? 'success' : 'active'"
      class="progress-bar"
    ></el-progress>

    <!-- 文件列表 -->
    <ul v-if="fileList.length > 0" class="file-list">
      <li v-for="(file, index) in fileList" :key="index">
        {{ file.name }} ({{ (file.size / 1024).toFixed(2) }} KB)
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [], // 存储选中的文件
      uploading: false, // 是否正在上传
      progress: 0 // 上传进度
    };
  },
  methods: {
    // 选择文件
    handleFileChange(file) {
      this.fileList.push(file.raw); // 只存储文件原始对象
    },

    // 上传文件
    async uploadFiles() {
      if (this.fileList.length === 0) return;

      this.uploading = true;
      this.progress = 0;

      const formData = new FormData();
      this.fileList.forEach(file => {
        formData.append("files[]", file); // 多文件上传
      });

      try {
        // 模拟上传 (假设上传到 /upload)
        await this.fakeUpload(formData);
      } catch (error) {
        console.error("上传失败", error);
      }

      this.uploading = false;
      this.fileList = []; // 清空文件列表
    },

    // 模拟上传 (你可以替换为真实 API 请求)
    fakeUpload(formData) {
      return new Promise(resolve => {
        let progressInterval = setInterval(() => {
          if (this.progress >= 100) {
            clearInterval(progressInterval);
            resolve();
          } else {
            this.progress += 10;
          }
        }, 300);
      });
    }
  }
};
</script>

<style scoped>
.upload-container {
  width: 400px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 5px;
  text-align: center;
}
.upload-box {
  margin-bottom: 10px;
}
.progress-bar {
  margin-top: 10px;
}
.file-list {
  list-style: none;
  padding: 0;
  margin-top: 10px;
}
.file-list li {
  font-size: 14px;
  color: #333;
}
</style>
